package isssr.dao.src;

import isssr.dao.exception.DAOException;
import isssr.dao.exception.HibernateDAOException;
import isssr.entity.src.User;

import java.io.Serializable;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class HibernateDAOCommons implements Serializable {

	private SessionFactory sessionFactory;

	public HibernateDAOCommons(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	protected Session openSession()
	{
		Session newSession = this.sessionFactory.openSession();
		return newSession;
	}
	
	protected void closeSession(Session session)
	{
		session.close();
		return;
	}
	
	protected String buildErrorMessage(String operationName)
	{
		return "Error performing " + operationName + " on record type " + User.class;
	}
	
	protected HibernateDAOException generateDAOException(Exception ex, String operationType)
	{
		String errorMessage = buildErrorMessage(operationType);
		HibernateDAOException daoEx = new HibernateDAOException(errorMessage);
		daoEx.initCause(ex);
		
		return daoEx;
	
	}
	
	
	protected void insert(Object entity) throws DAOException
	{
		Session session = null;
		
		try
		{
			session = openSession();
			session.save(entity);
			session.flush();
		}
		catch(Exception ex)
		{
			String errorOperation = "Insert";
			throw generateDAOException(ex, errorOperation);
		}
		finally
		{
			closeSession(session);
		}
	}
	

	protected void update(Object entity) throws DAOException {
		
		Session session = null;
		
		try
		{
			session = openSession();
			session.update(entity);
			session.flush();
		}
		catch(Exception ex)
		{
			String operationType = "Update";
			throw generateDAOException(ex, operationType);
		}
		finally
		{
			closeSession(session);
		}

	}

	protected void delete(Object entity) throws DAOException {

		Session session = null;
		
		try
		{
			session = openSession();
			session.delete(entity);
			session.flush();
		}
		catch(Exception ex)
		{
			String operationType = "Delete";
			throw generateDAOException(ex, operationType);
		}
		finally
		{
			closeSession(session);
		}
	}

}
